﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using GoodStuff.Security;
using System.Web.Security;

namespace GoodStuff.Web
{
    public interface ICookieHelper
    {
        void SetCookieValue(string name, string value);
        string GetCookieValue(string name);
    }

    /// <summary>
    /// Helper class to read and write encrypted cookies using the machine key.
    /// </summary>
    public class SecureCookieHelper : ICookieHelper
    {
        public void SetCookieValue(string name, string value)
        {
            HttpCookie newCookie = new HttpCookie(name);
            newCookie.Value = MachineKeyCryptography.Encode(value, CookieProtection.All);
            HttpContext.Current.Response.Cookies.Add(newCookie);

            //web trick - overwrite any existing request cookie. So that the NEXT GetSessionKey will return this one.
            HttpContext.Current.Request.Cookies.Add(newCookie);    
        }

        public string GetCookieValue(string name)
        {
            HttpCookie sessionCookie = HttpContext.Current.Request.Cookies[name];
            if (sessionCookie != null)
            {
                string keyValue = MachineKeyCryptography.Decode(sessionCookie.Value, CookieProtection.All);
                return keyValue;
            }

            return null;
        }
    }
}
